#include "database.h"
#include "exceptions.h"
#include "log.h"


namespace Database
{

using namespace Logging;

Database::Database(const string& path)
    : path_(path)
{
    Log(LL_DEBUG) << "path=" << path;
}


Database::~Database()
{
    for(auto entry : tables_)
        delete entry.second;
}


Table& Database::openTable(const string& name)
{
    // FIXME - executing this section under a lock isn't ideal, as it will create a barrier
    // preventing multiple threads acquiring tables simultaneously.
    std::lock_guard<std::mutex> lock(lockOpen_);

    const auto it = tables_.find(name);
    if(it != tables_.end())
        return it->second->open();

    tables_[name] = new Table(name);
    return tables_[name]->open();
}


void Database::dropTable(const string& name)
{
    // TODO: acquire read lock on table
    // TODO: unlink table files
    // TODO: remove table entry from tables_
}

}   // namespace Database
